<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sa="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>Layui 表格示例</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
</head>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <table id="meetingRoomTable" lay-filter="meetingRoomTable"></table>
    </div>
</div>

<script type="text/html" id="toolbar">
    <button class="layui-btn layui-btn-normal" lay-event="prevWeek">上一周</button>
    <button class="layui-btn layui-btn-normal" lay-event="currentWeek">当前周</button>
    <button class="layui-btn layui-btn-normal" lay-event="nextWeek">下一周</button>
    <button class="layui-btn layui-btn-normal" lay-event="reserve">预约</button>
</script>
<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:inline="javascript">
    layui.use(['table', 'laydate'], function () {
        let baseURL = /*[[@{/}]]*/ '';
        let table = layui.table;
        let form = layui.form;
        let $ = layui.jquery;
        const laydate = layui.laydate;

        // 初始化日期
        let currentDate = new Date();
        let currentYear = currentDate.getFullYear();
        let currentMonth = currentDate.getMonth();
        let currentDay = currentDate.getDate();

        // 获取本周的日期范围
        function getWeekDates(date) {
            const start = new Date(date);
            start.setDate(start.getDate() - start.getDay());
            const end = new Date(start);
            end.setDate(end.getDate() + 6);
            return {start, end};
        }

        // 更新表格列
        function updateTableColumns(start, end) {
            const columns = [
                {field: 'roomName', title: '会议室', sort: true, width: 100}
            ];
            for (let i = 0; i < 7; i++) {
                const date = new Date(start);
                date.setDate(date.getDate() + i);

                // 获取星期几（0: 周日, 1: 周一, ..., 6: 周六）
                const dayOfWeek = date.getDay();
                const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                const weekDayName = weekDays[dayOfWeek];

                columns.push({
                    field: 'day' + i,
                    title: `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} (${weekDayName})`
                });
            }
            return columns;
        }

        // 从后端获取会议室列表
        function fetchMeetingRooms() {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: baseURL + 'department/session/getDepartmentId', // 后端接口地址
                    type: 'get',
                    contentType: 'application/json',
                    success: function (response) {
                        window.departmentId = response.data;
                        $.ajax({
                            url: baseURL + 'meeting/reservation/getMeetByDepartment?departmentId=' + response.data, // 替换为实际的后端接口地址
                            type: 'GET',
                            success: function (response) {
                                resolve(response.data);
                            },
                            error: function (xhr, status, error) {
                                reject(error);
                            }
                        });
                    },
                    error: function (xhr, status, error) {
                        reject(error);
                    }
                });
            });
        }

        // 为每个会议室获取预约信息
        function fetchReservationsForRooms(rooms) {
            return Promise.all(rooms.map(room => {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: baseURL + 'meeting/reservation/reservationListByUserIdAndRoomId?roomId=' + room.roomId, // 替换为实际的后端接口地址
                        type: 'GET',
                        success: function (response) {
                            if (response.code === 1000) {
                                room.reservations = response.data;
                            } else {
                                room.reservations = [];
                            }
                            resolve(room);
                        },
                        error: function (xhr, status, error) {
                            console.error('会议室ID:', room.roomId, '获取预约信息失败:', error);
                            room.reservations = [];
                            resolve(room);
                        }
                    });
                });
            }));
        }

// 初始化表格
        function initTable() {
            fetchMeetingRooms().then(rooms => {
                return fetchReservationsForRooms(rooms);
            }).then(roomsWithReservations => {
                const weekDates = getWeekDates(currentDate);
                const columns = updateTableColumns(weekDates.start, weekDates.end);

                // 构建表格数据
                const tableData = roomsWithReservations.map(room => {
                    const row = {roomName: room.roomName};
                    for (let i = 0; i < 7; i++) {
                        const date = new Date(weekDates.start);
                        date.setDate(date.getDate() + i);
                        const reservationsForDay = room.reservations.filter(r => r.reservationData === date.toISOString().split('T')[0]);
                        if (reservationsForDay.length > 0) {
                            const reservationDetails = reservationsForDay.map(reservation => {
                                return `时间: ${reservation.startTime} - ${reservation.endTime}<br>`; // 使用 <div> 包裹每个预约事件
                            }).join(''); // 每个预约事件之间自然换行
                            row[`day${i}`] = reservationDetails;
                        } else {
                            row[`day${i}`] = ''; // 显示为空字符串
                        }
                    }
                    return row;
                });

                table.render({
                    elem: '#meetingRoomTable',
                    cols: [columns.map(col => {
                        if (col.field.startsWith('day')) {
                            return {
                                ...col,
                                templet: function (d) {
                                    return d[col.field] || ''; // 确保返回的是 HTML 字符串
                                }
                            };
                        }
                        return col;
                    })],
                    data: tableData,
                    page: false,
                    toolbar: '#toolbar',
                    rowHeight: 200
                });
            }).catch(error => {
                console.error('Error fetching meeting rooms and reservations:', error);
            });
        }

        initTable();
        table.on('toolbar(meetingRoomTable)', function (obj) {
            if (obj.event === 'prevWeek') {
                window.prevWeek();
            } else if (obj.event === 'currentWeek') {
                window.currentWeek();
            } else if (obj.event === 'nextWeek') {
                window.nextWeek();
            } else if (obj.event === 'reserve') {
                window.reserve();
            }
        });
        window.prevWeek = function () {
            currentDate.setDate(currentDate.getDate() - 7);
            initTable();
        }
        window.currentWeek = function () {
            currentDate = new Date();
            initTable();
        }
        window.nextWeek = function () {
            currentDate.setDate(currentDate.getDate() + 7);
            initTable();
        }
        window.reserve = function () {
            location.href = baseURL + "page/meeting/fullcalendar/index"
        }
    });
</script>
</body>
</html>